/**
 * 用户管理
 */
package com.sys.console.action;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sys.console.business.SysRoleService;
import com.sys.console.business.SysUserService;
import com.sys.console.cookie.Constant_Cookie;
import com.sys.console.mapper.Sys_User_RoleMapper;
import com.sys.console.pojo.Sys_Role;
import com.sys.console.pojo.Sys_User;
import com.sys.console.pojo.Sys_UserUpdatePassword;
import com.sys.console.pojo.Sys_User_Role_Key;
import com.sys.object.common.ObjException;
import com.sys.object.common.ObjResultCode;
import com.sys.object.common.ObjResultException;
import com.sys.object.common.ObjResultJSON;
import com.sys.object.common.page.PageBean;

/**
 * @author HS
 * 
 */
@Controller
public class SysUserAction {

	@Autowired SysUserService sysUserService;
	@Autowired SysRoleService sysRoleService;
	@Autowired Sys_User_RoleMapper sysUserRoleMapper;

	
    
    /**
	 * 用户列表
	 */
	@RequestMapping(value = "/sysUserList.do" ,method=RequestMethod.GET)
	public String sysUserList(PageBean pageBean, Model model, Sys_User user) {
				
		Integer enable = user.getEnable();
		String contact = user.getContact();
		String username = user.getUsername();
		String tel = user.getTel();
		
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			pageBean = sysUserService.queryPageList(user, pageBean);
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("startRow", pageBean.getStartRow());
			model.addAttribute("entity", user);
			model.addAttribute("enable", enable);
			model.addAttribute("username", username);
			model.addAttribute("tel", tel);
			if(StringUtils.hasText(contact)){
				model.addAttribute("contact", URLDecoder.decode(contact,"UTF-8"));
				model.addAttribute("url_contact",URLEncoder.encode(contact,"UTF-8"));
			}

		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.USER_LOGIN_ERROR);
			}
			model.addAttribute("ret", ret);
			e.printStackTrace();
		}

		return "/system/user/list";
	}

	/**
	 * 删除
	 * 
	 * @param record
	 * @return
	 */
	@RequestMapping("/deleteSysUser.do")
	@ResponseBody
	public ObjResultException<String> sysUserDelete(int id) {
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			int success = sysUserService.delete(id);

			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
			} else {
				ret.setResultCode(ObjResultCode.SYS_USER_DELETE_FAILED);
			}
		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		}
		return ret;
	}
	
	/**
	 * 判断用户名是已经被注册
	 * 
	 * @param record
	 * @return
	 */
	@RequestMapping(value="/sysUserIsExists.do",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String sysUserIsExists(Sys_User user) {
				
		boolean isExists = false;
		
		if(StringUtils.hasText(user.getUsername())){
			try {
				int success = sysUserService.selectExistsByUsername(user);
				if(success==0){
					isExists = true; //用户名不存在
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return String.valueOf(isExists);
	}
	
	/**
	 * 新增用户
	 * @return
	 */
	@RequestMapping(value = "/queryUserInfo.do", method = RequestMethod.GET)
	public String queryUserInfo(Model model) {
		try {
			Sys_User sysUser = (Sys_User) SecurityUtils.getSubject().getSession().getAttribute(Constant_Cookie.CURRENT_USER_SESSION);
			Sys_User user = sysUserService.queryByPrimaryKey(sysUser.getUid());
			model.addAttribute("entity", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/system/user/userinfo";
	}
	
	
	/**
	 * 新增用户
	 * @return
	 */
	@RequestMapping(value = "/addSysUser.do", method = RequestMethod.GET)
	public String add(Model model,String id) {
		try {
			Sys_User user = sysUserService.queryByPrimaryKey(Integer.parseInt(id));
			model.addAttribute("user", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/system/user/add";
	}
	
	/**
	 * 新增用户
	 * @return
	 */
	@RequestMapping(value = "/addSysUserByLayer.do", method = RequestMethod.GET)
	public String addSysUserByLayer(Model model,String id) {
		try {
			Sys_User user = sysUserService.queryByPrimaryKey(Integer.parseInt(id));
			model.addAttribute("user", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/system/user/addLayer";
	}
	
	/**
	 * 新增用户
	 * @return
	 */
	@RequestMapping(value = "/addSysUser.do", method = RequestMethod.POST)
	public String add(HttpServletRequest request,HttpServletResponse response,Sys_User sysUser,Model model) {
		ObjResultException<String> ret = new ObjResultException<String>();

		try {
			int success = sysUserService.saveSysUser(sysUser);

			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
			} else {
				ret.setResultCode(ObjResultCode.ROLE_ADD_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		}
		return "redirect:/sysUserList.do";
	}
	
	/**
	 * 新增用户
	 * @return
	 */
	@RequestMapping(value = "/addSysUserJson.do", method = RequestMethod.POST)
	@ResponseBody
	public ObjResultJSON<Sys_User> addSysUserJson(@RequestBody Sys_User sysUser,Model model) {
		ObjResultJSON<Sys_User> ret = new ObjResultJSON<Sys_User>();

		try {
			int success = sysUserService.saveSysUser(sysUser);

			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
				ret.setData(sysUser);
			} else {
				ret.setResultCode(ObjResultCode.ROLE_ADD_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		}
		return ret;
	}


	/**
	 * 给用户授权（角色）
	 */
	@RequestMapping(value = "/sysUserAuthority.do", method = RequestMethod.GET)
	public String sysUserAuthority(Model model,Integer id) {
		try {
			Sys_User user = sysUserService.queryByPrimaryKey(id);
			model.addAttribute("user",user);
			ArrayList<Sys_Role> rolelist = sysRoleService.selectByList();
			model.addAttribute("rolelist",rolelist);
		} catch (Exception e) {
			
		}
		return "/system/user/authority";
	}
	
	/**
	 * 给用户授权（角色）
	 */
	@RequestMapping(value = "/sysUserAuthorityLayer.do", method = RequestMethod.GET)
	public String sysUserAuthorityLayer(Model model,Integer id) {
		try {
			Sys_User user = sysUserService.queryByPrimaryKey(id);
			model.addAttribute("user",user);
			ArrayList<Sys_Role> rolelist = sysRoleService.selectByList();
			model.addAttribute("rolelist",rolelist);
		} catch (Exception e) {
			
		}
		return "/system/user/authorityLayer";
	}
	
	/**
	 * 获取用户角色
	 */
	@RequestMapping("/userRoleAjaxList.do")
	@ResponseBody
	public ObjResultJSON<ArrayList<Sys_Role>> userRoleAjaxList(HttpServletRequest request,HttpServletResponse response, Model model,Integer id) {
		
		ObjResultException<String> ret = new ObjResultException<String>();
		ObjResultJSON<ArrayList<Sys_Role>> retjson = new  ObjResultJSON<ArrayList<Sys_Role>>();
		try {
		
			ArrayList<Sys_Role> list = sysRoleService.selectByUid(id);
			
			if(list!=null&&list.size()>0){
				retjson.setData(list);
				retjson.setResultCode(ObjResultCode.OK);
			}else{
				retjson.setResultCode(ObjResultCode.DATA_ERROR);
			}
		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.DATA_ERROR);
			}
			e.printStackTrace();
		}
		return retjson;
	}
	
	/**
	 * 保存用户角色
	 */
	@RequestMapping(value = "/saveSysUserRole.do")
	@ResponseBody
	public ObjResultException<String> saveSysUserRole(Integer uid,String roles) {
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			if(uid>0){
				sysUserRoleMapper.deleteByUid(uid);
				if(StringUtils.hasText(roles)){
					String[] rids = roles.split(",");
					if(rids.length>0){
						for(int i=0; i<rids.length;i++){
							Sys_User_Role_Key record = new  Sys_User_Role_Key();
							record.setUid(uid);
							record.setRid(Integer.parseInt(rids[i]));
							sysUserRoleMapper.insert(record);
						}
					}
				}
			}
			ret.setResultCode(ObjResultCode.OK);
		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.DATA_ERROR);
			}
			e.printStackTrace();
		}
		return ret;
	}
	
    /**
	 * 用户选择分页列表
	 */
	@RequestMapping(value = "/selectUserList.do")
	public String selectUserList(PageBean pageBean, Model model, Sys_User user,String account,String contact) {
			
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			pageBean = sysUserService.queryPageList(user, pageBean);
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("startRow", pageBean.getStartRow());
			model.addAttribute("entity", user);
			
			if(StringUtils.hasText(account)){
				model.addAttribute("account", URLDecoder.decode(account,"UTF-8"));
				model.addAttribute("url_account",URLEncoder.encode(account,"UTF-8"));
			}
			
			if(StringUtils.hasText(contact)){
				model.addAttribute("contact", URLDecoder.decode(contact,"UTF-8"));
				model.addAttribute("url_contact",URLEncoder.encode(contact,"UTF-8"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.DATA_ERROR);
			}
			model.addAttribute("ret", ret);
		}

		return "/system/user/SelectUserList";
	}

	/**
	 * 修改系统用户状态
	 */
	@RequestMapping("/updateSysUserStatus.do")
	@ResponseBody
	public ObjResultException<String> updateSysUserStatus(int uid,int enable) {
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			
			Sys_User user = new Sys_User();
			
			user.setUid(uid);
			user.setEnable(enable);
			
			int success = sysUserService.updateStatus(user);

			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
			} else {
				ret.setResultCode(ObjResultCode.SYS_USER_STATUS_UPDATE_FAILED);
			}
		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		}
		return ret;
	}
	
	/**
	 * 修改密码 GET (登陆用户)
	 * 
	 * @param offices
	 * @return
	 */
	@RequestMapping(value = "/updateSysUserPassword.do", method = RequestMethod.GET)
	public String updateSysUserPassword(Model model) {
		try {
			Sys_User sysUser = (Sys_User) SecurityUtils.getSubject().getSession().getAttribute(Constant_Cookie.CURRENT_USER_SESSION);
			Sys_User record = sysUserService.queryByPrimaryKey(sysUser.getUid());
			model.addAttribute("user", record);

		} catch (Exception e) {

			e.printStackTrace();
		}
		return "/system/user/SysUserUpdataPassword";
	}
	
	/**
	 * 重置密码 Post (登陆用户)
	 */
	@RequestMapping(value = "/updateSysUserPasswordJson.do", method = RequestMethod.POST)
	@ResponseBody
	public ObjResultException<String> updateSysUserPasswordJson(@RequestBody Sys_UserUpdatePassword user, Model model) {
		Sys_User sys_user = (Sys_User) SecurityUtils.getSubject().getSession().getAttribute(Constant_Cookie.CURRENT_USER_SESSION);
		ObjResultException<String> ret = new ObjResultException<String>();
		if(sys_user==null || sys_user.getUid()==null){
			ret.setResultCode(ObjResultCode.USER_SESSION_EXIT_LOGIN);
			return ret;
		}
			user.setUid(sys_user.getUid());
		try {
			int success = sysUserService.updatePassword(user);
			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
			} else {
				ret.setResultCode(ObjResultCode.USER_PASSWORD_UPDATE_FAILURE);
			}
		} catch (Exception e) {

			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.USER_PASSWORD_UPDATE_FAILURE);
			}
		}
		return ret;
	}
	
	/**
	 * 重置密码 GET
	 * 
	 * @param officesupdateSysUserPassword
	 * @return
	 */
	@RequestMapping(value = "/sysUserResetPass.do", method = RequestMethod.GET)
	public String sysUserPasswordUpdate(Sys_User user, Model model,	String id) {
		try {

			Sys_User record = sysUserService.queryByPrimaryKey(Integer.parseInt(id));
			model.addAttribute("user", record);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return "/system/user/updatepass";
	}
	
	/**
	 * 重置密码 Post
	 */
	@RequestMapping(value = "/sysUserPassUpdateJson.do", method = RequestMethod.POST)
	@ResponseBody
	public ObjResultException<String> sysUserPassUpdateJson(@RequestBody Sys_UserUpdatePassword user, Model model) {
		ObjResultException<String> ret = new ObjResultException<String>();
		try {
			int success = sysUserService.updateResetPass(user);
			
			if (success > 0) {
				ret.setResultCode(ObjResultCode.OK);
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		} catch (Exception e) {
			if (e.getClass().equals(ObjException.class)) {
				ret.setResultCode(((ObjException) e).getCode());
			} else {
				ret.setResultCode(ObjResultCode.ERROR);
			}
		}
		return ret;
	}
}
